/*
 * 
 * Copyright 2010 David H Pollack
 * 
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * 
 *     http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License. 
 * 
 * 
 */

package fantasy;

import java.io.IOException;
import java.net.URLDecoder;
import java.util.List;

import javax.jdo.PersistenceManager;
import javax.jdo.Query;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.oauth.OAuthException;

import com.google.appengine.api.users.User;
import com.google.appengine.api.users.UserService;
import com.google.appengine.api.users.UserServiceFactory;
import com.simpleyql.Api;
import com.simpleyql.ApiFactory;
import com.simpleyql.QueryResult;


public class ReturnServlet extends HttpServlet {

	/**
	 * 
	 */
	private static final long serialVersionUID = -5349303332860727760L;

	protected void service(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {

		// Set to expire far in the past.
		resp.setHeader("Expires", "Sat, 6 May 1995 12:00:00 GMT");
		// Set standard HTTP/1.1 no-cache headers.
		resp.setHeader("Cache-Control", "no-store, no-cache, must-revalidate");
		// Set IE extended HTTP/1.1 no-cache headers (use addHeader).
		resp.addHeader("Cache-Control", "post-check=0, pre-check=0");
		// Set standard HTTP/1.0 no-cache header.
		resp.setHeader("Pragma", "no-cache");

		UserService userService = UserServiceFactory.getUserService();
        User user = userService.getCurrentUser();
        
		PersistenceManager pm = PMF.get().getPersistenceManager();
        
	    Query query = pm.newQuery(UserTable.class);
	    query.setFilter("userkey == nickNameParam");
	    query.declareParameters("String nickNameParam");
	    
	    try {
	    	List<UserTable> uquery = (List<UserTable>) query.execute(user.getNickname());
		    if (uquery.isEmpty()) {
				
		    	UserTable appUser = new UserTable(user.getNickname(), URLDecoder.decode(req.getParameter("authdata"), "US-ASCII"));
	        	try {
	            	pm.makePersistent(appUser);
	        	} finally {
	            	pm.close();
	        	}
		    }
	    } finally {
	        query.closeAll();
	    }
        getServletConfig().getServletContext().getRequestDispatcher("/confirm.jsp").forward(req, resp);

        /*  All this is old code that I'll eventually delete
        
        Api api = ApiFactory.getApiInstance(
	            "dj0yJmk9NGVDelJyN2MzWW5zJmQ9WVdrOVRFcGFaalZrTkdrbWNHbzlNak16TVRFNE5qWXkmcz1jb25zdW1lcnNlY3JldCZ4PTM2",
	            "91b08a397dc663f4372f6a4fa31e693f6ab7bf54",
	            "http://dhpollack944.appspot.com/simpleyqlcallback/",
	            false, null);
		String authdata = req.getParameter("authdata");
	    
		resp.getWriter().println("It still works!");
        resp.getWriter().println(user.getNickname());
		resp.getWriter().println(authdata);
        UserTable appUser = new UserTable(user.getNickname(), authdata);
        PersistenceManager pm = PMF.get().getPersistenceManager();

		try {
			QueryResult qr = api.query("http://social.yahooapis.com/v1/me/guid", authdata);
			resp.getWriter().println(qr.getText());
		} catch (OAuthException e) {
			// TODO Auto-generated catch block
			resp.getWriter().println("Actually, it didn't work.");
			e.printStackTrace();
		}
		
		resp.getWriter().println("End of reponse.");
		*/        

		
		
		/*		
		// Get my yahoo GUID
		//http://social.yahooapis.com/v1/me/guid
        try {
            URL url = new URL("http://local.yahooapis.com/MapsService/V1/geocode?appid=YD-9G7bey8_JXxQP6rxl.fBFGgCdNjoDMACQA--&street=701+First+Ave&city=Sunnyvale&state=CA");
            BufferedReader reader = new BufferedReader(new InputStreamReader(url.openStream()));
            String line;

            while ((line = reader.readLine()) != null) {
            	resp.getWriter().println(line);
            }
            reader.close();

        } catch (MalformedURLException e) {
            // ...
        } catch (IOException e) {
            // ...
        }		
		 */	
	}
}